package com.ruoyi.framework.oss.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.oss.core.OssClient;
import com.ruoyi.framework.oss.entity.UploadResult;
import com.ruoyi.framework.oss.factory.OssFactory;
import com.ruoyi.framework.oss.service.IFileService;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.service.ISysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author zouhuu
 * @description 文件服务层
 * @date 2022/07/25 14:40:08
 */
@Service
public class IFileServiceImpl implements IFileService {

    @Autowired
    private ISysOssService sysOssService;

    @Override
    public UploadResult upload(MultipartFile file, String source) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
        // 保存文件信息
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(originalfileName);
        oss.setService(storage.getConfigKey());
        oss.setFileSize(file.getSize());
        oss.setSource(source);
        sysOssService.insertSysOss(oss);
        return uploadResult;
    }
}
